import { RouteRecordRaw } from "vue-router";
import { constantRoutes } from "@/router";
import { store, useUserStore } from "@/store";

const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");

export const usePermissionStore = defineStore("permission", () => {
  /** 所有路由，包括静态和动态路由 */
  const routes = ref<RouteRecordRaw[]>([]);
  /** 混合模式左侧菜单 */
  const mixLeftMenus = ref<RouteRecordRaw[]>([]);

  /**
   * 生成动态路由
   */
  function generateRoutes() {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      const { isAdmin } = useUserStore().user;
      let data: RouteVO[] = [];
      if (isAdmin === 1) {
        data = [
          {
            path: "/admin/users",
            name: "users",
            component: "Layout",
            children: [
              {
                path: "/admin/users",
                name: "users",
                component: "users/index",
                meta: { title: "用户管理", icon: "user", keepAlive: true },
              },
            ],
          },
          {
            path: "/admin/menu",
            component: "Layout",
            name: "menu",
            redirect: "/admin/article",
            meta: { title: "文章管理", icon: "menu" },
            children: [
              {
                path: "/admin/article",
                name: "article",
                component: "menu/article/index",
                meta: { title: "文章列表", icon: "article", keepAlive: true },
              },
              {
                path: "/admin/category",
                name: "category",
                component: "menu/category/index",
                meta: { title: "类别管理", icon: "article", keepAlive: true },
              },
            ],
          },
        ];
      } else {
        data = [
          {
            path: "/study",
            component: "Layout",
            name: "study",
            meta: { title: "在线学习", icon: "study" },
            redirect: "/admin/dashboard",
            children: [
              {
                path: "/user/study/article",
                name: "studyArticle",
                component: "study/article/index",
                meta: { title: "浏览文章", icon: "article", keepAlive: true },
              },
              {
                path: "/user/study/article/:id",
                name: "detail",
                component: "study/article/detail",
                meta: { title: "浏览文章", hidden: true },
              },
              {
                path: "/user/study/homework",
                name: "homework",
                component: "study/homework/index",
                meta: { title: "习题练习", icon: "homework", keepAlive: true },
              },
            ],
          },
          {
            path: "/user",
            component: "Layout",
            name: "assess",
            redirect: "/user/assess",
            children: [
              {
                path: "/user/assess",
                name: "assess",
                component: "study/assess/index",
                meta: { title: "考核评价", icon: "article", keepAlive: true },
              },
            ],
          },
        ];
      }
      data.push({
        path: "/user",
        name: "user",
        component: "Layout",
        children: [
          {
            path: "/user/editUser",
            name: "editUser",
            component: "editUser/index",
            meta: { title: "修改信息", icon: "user", keepAlive: true },
          },
        ],
      });
      const dynamicRoutes = transformRoutes(data);

      routes.value = constantRoutes.concat(dynamicRoutes);
      resolve(dynamicRoutes);
    });
  }

  /**
   * 混合模式菜单下根据顶部菜单路径设置左侧菜单
   *
   * @param topMenuPath - 顶部菜单路径
   */
  const setMixLeftMenus = (topMenuPath: string) => {
    const matchedItem = routes.value.find((item) => item.path === topMenuPath);
    if (matchedItem && matchedItem.children) {
      mixLeftMenus.value = matchedItem.children;
    }
  };

  return {
    routes,
    generateRoutes,
    mixLeftMenus,
    setMixLeftMenus,
  };
});

/**
 * 转换路由数据为组件
 */
const transformRoutes = (routes: RouteVO[]) => {
  const asyncRoutes: RouteRecordRaw[] = [];
  routes.forEach((route) => {
    const tmpRoute = { ...route } as RouteRecordRaw;
    // 顶级目录，替换为 Layout 组件
    if (tmpRoute.component?.toString() == "Layout") {
      tmpRoute.component = Layout;
    } else {
      // 其他菜单，根据组件路径动态加载组件
      const component = modules[`../../views/${tmpRoute.component}.vue`];
      if (component) {
        tmpRoute.component = component;
      } else {
        tmpRoute.component = modules[`../../views/error-page/404.vue`];
      }
    }

    if (tmpRoute.children) {
      tmpRoute.children = transformRoutes(route.children as RouteVO[]);
    }

    asyncRoutes.push(tmpRoute);
  });

  return asyncRoutes;
};

/**
 * 在组件外使用 Pinia store 实例
 * @see https://pinia.vuejs.org/core-concepts/outside-component-usage.html
 */
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}

// [
//   {
//     path: "/doc",
//     component: "Layout",
//     redirect: "https://juejin.cn/post/7228990409909108793",
//     name: "/doc",
//     meta: {
//       title: "平台文档",
//       icon: "document",
//       hidden: false,
//       alwaysShow: false,
//       params: null,
//     },
//     children: [
//       {
//         path: "internal-doc",
//         component: "demo/internal-doc",
//         name: "InternalDoc",
//         meta: {
//           title: "平台文档(内嵌)",
//           icon: "document",
//           hidden: false,
//           alwaysShow: false,
//           params: null,
//         },
//       },
//       {
//         path: "https://juejin.cn/post/7228990409909108793",
//         name: "Https://juejin.cn/post/7228990409909108793",
//         meta: {
//           title: "平台文档(外链)",
//           icon: "el-icon-Link",
//           hidden: false,
//           alwaysShow: false,
//           params: null,
//         },
//       },
//     ],
//   },
// ]
